var gulp = require('gulp');
var sass = require('gulp-sass');  //编译scss
var cleanCSS = require('gulp-clean-css');//压缩css
var gulpautoprefixer = require('gulp-autoprefixer');//自动添加前缀
var uglify = require('gulp-uglify'); //js 压缩混淆
var gulpImagemin = require('gulp-imagemin'); //图片压缩
var browserSync = require('browser-sync').create();  //浏览器自动重载
var reload      = browserSync.reload;

sass.compiler = require('node-sass');

gulp.task('scss',(cb)=>{
  gulp.src('static/**/*.scss')
  .pipe(sass().on('error', sass.logError))
  .pipe(gulpautoprefixer())
  .pipe(cleanCSS())
  .pipe(gulp.dest('public'))
  .pipe(reload({stream: true}))
  cb();
})

gulp.task('devUglifyJs', cb=>{
  gulp.src('static/**/*.js')
    .pipe(gulp.dest('public'))
  cb();
})

gulp.task('proUglifyJs', cb=>{
  gulp.src('static/**/*.js')
    .pipe(uglify({
      compress: {
        warnings: false,
        drop_console: true,  // 过滤 console
        drop_debugger: true  // 过滤 debugger
      }
    }))
    .pipe(gulp.dest('public'))
  cb();
})

gulp.task('imagemin', cb=>{
  gulp.src('static/img/*')
    .pipe(gulpImagemin())
    .pipe(gulp.dest('public/img'))
  cb();
})



//gulp 文件监听
gulp.task('watch',cb=>{   
  browserSync.init({
      proxy: "http://localhost:8081",
      files: ["public/**/*.*", "views/**", "static/**"],
      notify: false
  });
  gulp.watch('static/**/*.scss', gulp.series('scss'))
  gulp.watch('static/**/*.js', gulp.series('devUglifyJs'))
  gulp.watch('static/img/*', gulp.series('imagemin'))
  gulp.watch("views/*.html").on('change', reload);
  cb();
})

//依次执行任务   顺序为 scss 》 uglifyJs 》 imagemin 》 watch 》 default
gulp.task('dev',gulp.series('watch',gulp.series( 'scss', 'devUglifyJs', 'imagemin')), cb=>{
  cb();
})

//依次执行任务   顺序为 scss 》 proUglifyJs 》 imagemin 》 watch 》 default
gulp.task('pro',gulp.series( 'scss', 'proUglifyJs', 'imagemin'), cb=>{
  cb();
})